package cn.com.ethos.search.query;

import org.json.JSONException;
import org.json.JSONObject;

public class Request {

	private static final String KEY_QUERY = "query";
	private static final String KEY_PAGE = "page";
	private static final String KEY_SIZE = "size";

	private String query;
	private int page;
	private int size;

	public String getQuery() {
		return this.query;
	}

	public int getPage() {
		return this.page;
	}

	public int getSize() {
		return this.size;
	}

	private Request(String query, int page, int size) {
		super();
		this.query = query;
		this.page = page;
		this.size = size;
	}

	private Request() {
		super();
	}

	/**
	 * JSON Format 
	 * JSON object {query:'hello',page:1,size:20} 
	 * @param request
	 * @return SearchRequest
	 */
	static public Request parse(String request) throws JSONException,
			IllegalArgumentException {
		JSONObject obj = new JSONObject(request);
		String query = obj.getString(KEY_QUERY);
		int page = obj.getInt(KEY_PAGE);
		int size = obj.getInt(KEY_SIZE);
		if (page < 1) {
			page = 1;
		}
		if (size < 1) {
			throw new IllegalArgumentException(
					"The size in request should not less than 1");
		}
		return new Request(query, page, size);
	}
}
